<template>
  <el-dialog title="新增页面" :visible="dialogShow" @close="closeFn">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      :label-position="right"
      label-width="80px"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <!-- 富文本域 -->
      <el-form-item label="内容" prop="content">
        <vue-editor ref="VueEditor" v-model="formData.content" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="addFn">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 局部富文本域引入
import { VueEditor } from 'vue2-editor'
// 新增/编辑接口
import { setPagesList, editPagesId } from '@/api/page'
export default {
  components: { VueEditor },
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      right: 'right', // 表单中的文字对齐
      formData: {
        content: '',
        title: ''
      },
      // 验证
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '标题长度为2到10位', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { min: 2, max: 300, message: '内容长度为2到300位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 新增页面
    async addFn() {
      // 富文本域中的方法,通过refs属性调用
      const result = this.$refs.VueEditor.quill.getLength()
      if (result === 1) {
        this.formData.content = ''
      }
      await this.$refs.form.validate()// 验证
      console.log('通过验证')
      if (this.formData.id) {
        await editPagesId(this.formData)
        this.$message.success('编辑成功!')
      } else {
        // 新增
        await setPagesList(this.formData)
        this.$message.success('新增成功!')
      }
      // 提示父组件更新页面
      await this.$emit('updateEvnet')
      // 关闭
      this.closeFn()
    },
    //
    Formatblur() {
      this.$refs.form.validateField('content')
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:dialogShow', false)
      // 清空数据
      this.formData = {
        content: '',
        title: ''
      }
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
